package cmd

import (
	"Server/internal/middleware/auth"
	"context"
	"github.com/gogf/gf/v2/os/glog"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"

	"Server/internal/controller"
)

var (
	Main = gcmd.Command{
		Name:  "server",
		Usage: "server",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			s := g.Server()
			SetDefaultHandler()

			s.Group("/v1", func(group *ghttp.RouterGroup) {
				group.Middleware(auth.AuthMiddleware().MiddlewareHandlerResponse)
				group.Middleware(auth.AuthMiddleware().CORS)
				group.Middleware(auth.AuthMiddleware().Garbled)
				//不用鉴权的api
				group.Bind(
					controller.Hello,
					controller.LoginApi,
				)
				//要鉴权的api
				group.Group("/", func(group *ghttp.RouterGroup) {
					group.Middleware(auth.AuthMiddleware().Auth)
					group.Bind(controller.WebApi)
				})
			})
			s.Run()
			return nil
		},
	}
)

//SetDefaultHandler 替代默认的日志handler，禁止控制台输出，全部输出到文件
func SetDefaultHandler() {
	glog.SetHandlers(func(ctx context.Context, in *glog.HandlerInput) {
		m := map[string]interface{}{
			"stdout": true,
			"path":   g.Config().MustGet(ctx, "logger.path", "log/").String(), // 此处必须重新设置，才可以实现db的log写入文件
		}
		in.Logger.SetConfigWithMap(m)
		in.Next(ctx)
	})
}
